import time
import jwt

class Authenticated():
    def has_permission(self, request,*args):
        token = request.META.get('HTTP_TOKEN')
        if token:
            BOOLEAN = verify_bearer_token(token=token)
        else:
            BOOLEAN = False
        return BOOLEAN


def verify_bearer_token(token):
    try:
        jwt.decode(token, 'secret', algorithms=['HS256'])
        return True
    except:
        # '签名已过期
        return False


def create_token(user):
    payload = {"exp": int(time.time()) + 60*60, "sub": user.id, "username": user.username, }
    token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf8')
    return token
